package com.mju.service.impl;

import com.mju.service.IMailService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MailService implements IMailService {

  @Value("${spring.mail.username}")
  private String mailUsername;

  @Autowired private JavaMailSender javaMailSender;

  @Autowired private TemplateEngine templateEngine;

  /**
   * 激活账号邮件发送
   *
   * @param activationUrl 激活链接
   * @param email 邮箱
   */
  @SneakyThrows
  @Override
  public void sendMailForActivationAccount(String activationUrl, String email) {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
    //设置邮件主题
    message.setSubject("欢迎使用Mint商城 - 个人账号激活");
    // 设置邮件发送者
    message.setFrom(mailUsername);
    // 设置邮件接受者，可以多个
    message.setTo(email);
    // 设置邮件发送日期
    message.setSentDate(new Date());
    // 创建上下文环境
    Context context = new Context();
    context.setVariable("activationUrl", activationUrl);
    String text = templateEngine.process("activation-account.html", context);
    // 设置邮件正文
    message.setText(text, true);
    // 邮件发送
    javaMailSender.send(mimeMessage);
    log.info("激活邮件发送成功...");
  }
}
